//
//  SNHearDetailVc.m
//  project
//
//  Created by 黄建华 on 2017/12/9.
//  Copyright © 2017年 黄建华. All rights reserved.
//

#import "SNHearDetailVc.h"
#import "SNHeartChartView.h"
#import "SNHeartDetailTableViewCell.h"

#define LEFTWIDTH    30.0
#define SNHEARTBIG   [UIColor colorFromHex:0xFF2D55]
#define SNHEARTSMALL [UIColor colorFromHex:0x68E7FF]

@interface SNHearDetailVc () <UITableViewDelegate, UITableViewDataSource>
@property (nonatomic, strong) UIView           *headView;   //下拉视图
@property (nonatomic, strong) UITableView      *tableView;
@property (nonatomic, strong) NSMutableArray   *modelArray;
@property (nonatomic, strong) SNHeartChartView *ChartView;
@property (nonatomic, assign) SelectDateType   type;
@property (nonatomic, strong) UIView           *labelView;

@end

@implementation SNHearDetailVc

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self initTabelView];
}

- (void)initTabelView {
    _tableView                = [[UITableView alloc]initWithFrame:CGRectMake(0, 70+FitSimpleIpx(0, 20), HHHWIDTH, HHHHEIGHT - 70-FitSimpleIpx(0, 20)) style:UITableViewStylePlain];
    _tableView.delegate       = self;
    _tableView.dataSource     = self;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:_tableView];
    
    _headView                  = [[UIView alloc] init];
    _headView.frame            = SNFRAME(0, 0, HHHWIDTH, _tableView.height *0.6);
    _tableView.tableHeaderView = _headView;
    
    _ChartView = [[SNHeartChartView alloc] initWithFrame:SNFRAME(LEFTWIDTH, 0, HHHWIDTH - LEFTWIDTH, _headView.height *0.6)];
    [_headView addSubview:_ChartView];
    
    [self loadLabelValue];
    
    NSArray *arrayString = [NSArray arrayWithObjects:SN_Text(@"平均心率"), SN_Text(@"最高心率"), SN_Text(@"最低心率"), nil];
    for (int i = 0; i < 3; i++) {
        UILabel *unitLabel = [[UILabel alloc] init];
        unitLabel.textAlignment = NSTextAlignmentCenter;
        unitLabel.text          = arrayString[i];
        unitLabel.textColor     = SNCOLORGRAY;
        unitLabel.font          = SNSFONT(13.0);
        unitLabel.frame         = SNFRAME(HHHWIDTH /3 *i, 10 + 30, HHHWIDTH /3, 20);
        [_labelView addSubview:unitLabel];
    }
    
    UIView *bgView = [[UIView alloc] initWithFrame:SNFRAME(0, _labelView.bottom, screenWidth, 100)];
    [self.headView addSubview:bgView];
    bgView.backgroundColor = UIColorHEX(0xF2F4F5);
    
    UIView *bgView2 = [[UIView alloc] initWithFrame:SNFRAME(15,15, screenWidth-30, 70)];
    [bgView addSubview:bgView2];
    bgView2.layer.cornerRadius = 6;
    bgView2.backgroundColor = UIColorHEX(0xffffff);
    
    UIImageView *sleepImg = [[UIImageView alloc] init];
    sleepImg.frame = SNFRAME(15, 16, 38, 38);
    sleepImg.image = [UIImage imageNamed:@"心率222"];
    [bgView2 addSubview:sleepImg];
    
    UILabel *sleepTypeLabel = [[UILabel alloc] init];
    sleepTypeLabel.textAlignment = NSTextAlignmentLeft;
    sleepTypeLabel.frame         = SNFRAME(66, 25, 120, 20);
    sleepTypeLabel.textColor     = SNCOLORBLACK;
    sleepTypeLabel.text          = SN_Text(@"心率详情");
    sleepTypeLabel.font          = SNFONTMEDIUM(18);
    sleepTypeLabel.adjustsFontSizeToFitWidth = YES;
    [bgView2 addSubview:sleepTypeLabel];
    
    UIView *red = [[SNShadowView alloc] init];
    red.frame               = SNFRAME(bgView2.width/2, 30, 10, 10);
    red.backgroundColor     = SNHEARTBIG;
    red.layer.masksToBounds = YES;
    red.layer.cornerRadius  = red.width / 2.0;
    [bgView2 addSubview:red];
    
    UILabel *redLabel = [[UILabel alloc] init];
    redLabel.textAlignment = NSTextAlignmentLeft;
    redLabel.frame         = SNFRAME(red.center.x + 10, red.center.y-15, 65, 30);
    redLabel.textColor     = UIColorHEX(0x424242);
    redLabel.text          = SN_Text(@"心率过高");
    redLabel.numberOfLines = 0;
    redLabel.font          = SNFONTREGULAR(10);
    [bgView2 addSubview:redLabel];
    
    UIView *low = [[SNShadowView alloc] init];
    low.frame               = SNFRAME(redLabel.right +10, 30, 10, 10);
    low.backgroundColor     = SNHEARTSMALL;
    low.layer.masksToBounds = YES;
    low.layer.cornerRadius  = low.width / 2.0;
    [bgView2 addSubview:low];
    
    UILabel *lowLabel = [[UILabel alloc] init];
    lowLabel.textAlignment = NSTextAlignmentLeft;
    lowLabel.frame         = SNFRAME(low.center.x + 10, low.center.y-15, 65, 30);
    lowLabel.textColor     = UIColorHEX(0x424242);
    lowLabel.text          = SN_Text(@"心率过低");
    lowLabel.font          = SNFONTREGULAR(10);
    lowLabel.numberOfLines = 0;
    [bgView2 addSubview:lowLabel];
    
    [self selectType:SelectDateDay];
}

- (void)loadLabelValue {
    _labelView       = [[UIView alloc] init];
    _labelView.frame = SNFRAME(0, _headView.height *0.6, HHHWIDTH, _headView.height *0.2 -20);
    [_headView addSubview:_labelView];
    
    for (int i = 0; i < 3; i++) {
        UILabel *unitLabel = [[UILabel alloc] init];
        unitLabel.tag           = 100 + i;
        unitLabel.textAlignment = NSTextAlignmentCenter;
        unitLabel.textColor     = SNCOLORBLACK;
        unitLabel.font          = SNFONT(17.0);
        unitLabel.frame         = SNFRAME(HHHWIDTH /3 *i + 3, 10, HHHWIDTH /3, 20);
        [_labelView addSubview:unitLabel];
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (_type == 0) {
        return _modelArray.count;
    } else if (_type == 1) {
        return _modelArray.count;
    } else {
        return _modelArray.count;
    }
    //    return _modelArray.count ;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 40;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *identifier = @"SNHeartDetailTableViewCell";
    
    SNHeartDetailTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    
    if (nil == cell) {
        cell = [[SNHeartDetailTableViewCell alloc] initWithStyle:(UITableViewCellStyleDefault) reuseIdentifier:identifier];
    }
    
    [cell updateHeartCell:[_modelArray objectAtIndex:indexPath.row] withSelectType:_type];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    return cell;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)selectType:(SelectDateType)type {
    //    NSLog(@"周月年选择了>>>>>>%d",type);
    _type = type;
    
    HeartModel     *model = [HeartModel getHeartModelFromDBWith:SN_PublicClass.selectDate];
    NSMutableArray *array = [NSMutableArray array];
    _modelArray = [NSMutableArray array];
    if (type == SelectDateDay) {
        array = [NSMutableArray arrayWithArray:model.heartChartArray];
        
        for (int k = 0; k < model.heartAllValueArray.count; k++) {
            NSMutableArray *arr   = [[NSMutableArray alloc] init];
            NSString       *time  = [model.heartAllTimeArray objectAtIndex:k];
            NSString       *value = [model.heartAllValueArray objectAtIndex:k];
            [arr addObject:time];
            [arr addObject:value];
            [_modelArray addObject:arr];
        }
        
        _modelArray = (NSMutableArray *)[[_modelArray reverseObjectEnumerator] allObjects];
    } else {
        if (type == SelectDateWeek) {
            NSArray *weekArray = [NSArray arrayWithObjects:SN_Text(@"周日"), SN_Text(@"周一"), SN_Text(@"周二"), SN_Text(@"周三"), SN_Text(@"周四"), SN_Text(@"周五"), SN_Text(@"周六"), nil];
            for (int i = 0; i < 7; i++) {
                NSDate         *first       = [SN_PublicClass getMonthBeginAndEndWith:SN_PublicClass.selectDate withType:1];
                NSDate         *Date        = [first dateAfterDay:i];
                NSString       *firstString = [Date dateToDayString];
                NSString       *sss         = [NSString stringWithFormat:@"SELECT heartAve FROM HeartModel WHERE dateString ='%@' and dateString <='%@' and user_id = '%@'", firstString, [[NSDate date]dateToDayString], SN_USER.user_id];
                NSString       *heartValue  = [[HeartModel getUsingLKDBHelper]executeScalarWithSQL:sss arguments:nil];
                NSMutableArray *arr         = [[NSMutableArray alloc] init];
                [arr addObject:weekArray[i]];
                int heartValues = heartValue.intValue;
                [arr addObject:StrByInt(heartValues)];
                if (heartValues > 0) {
                    [_modelArray addObject:arr];
                }
                [array addObject:StrByInt(heartValues)];
            }
        }
        
        if (type == SelectDateMonth) {
            NSInteger monthCount = SN_PublicClass.selectDate.daysInMonth;
            for (int i = 0; i < monthCount; i++) {
                NSDate         *first       = [SN_PublicClass getMonthBeginAndEndWith:SN_PublicClass.selectDate withType:2];
                NSDate         *Date        = [first dateAfterDay:i];
                NSString       *firstString = [Date dateToDayString];
                NSString       *sss         = [NSString stringWithFormat:@"SELECT heartAve FROM HeartModel WHERE dateString ='%@' and dateString <='%@' and user_id = '%@'", firstString, [[NSDate date]dateToDayString], SN_USER.user_id];
                NSString       *heartValue  = [[HeartModel getUsingLKDBHelper]executeScalarWithSQL:sss arguments:nil];
                NSMutableArray *arr         = [[NSMutableArray alloc] init];
                [arr addObject:firstString];
                int heartValues = heartValue.intValue;
                [arr addObject:StrByInt(heartValues)];
                
                if (heartValues > 0) {
                    [_modelArray addObject:arr];
                }
                [array addObject:StrByInt(heartValues)];
            }
            _modelArray = (NSMutableArray *)[[_modelArray reverseObjectEnumerator] allObjects];
        }
    }
    
    [_ChartView UpdateViewWithType:type withArray:array];//主状态
    [_tableView reloadData];
    
    [self updateValueLabel:type];
}

- (void)updateValueLabel:(SelectDateType)type {
    NSString *heartAve = @"--";
    NSString *heartMax = @"--";
    NSString *heartMin = @"--";
    
    if (_type == SelectDateDay) {
        HeartModel *model = [HeartModel getHeartModelFromDBWith:SN_PublicClass.selectDate];
        heartAve = model.heartAve == 0 ? @"--" : [NSString stringWithFormat:@"%d bpm", model.heartAve];
        heartMax = model.heartAve == 0 ? @"--" : [NSString stringWithFormat:@"%d bpm", model.heartMax];
        heartMin = model.heartAve == 0 ? @"--" : [NSString stringWithFormat:@"%d bpm", model.heartMin];
    } else {
        NSArray  *time = [SN_PublicClass getBeginDateStringAndEndWith:SN_PublicClass.selectDate withType:_type];
        NSString *max  = [NSString stringWithFormat:@"SELECT MAX(heartAve) AS OrderTotal FROM HeartModel WHERE dateString >='%@' and dateString <='%@' and heartAve >0 and user_id = '%@'", [time firstObject], [time lastObject], SN_USER.user_id];
        NSString *maxs = [[HeartModel getUsingLKDBHelper]executeScalarWithSQL:max arguments:nil];
        heartMax = maxs.integerValue == 0 ? @"--" : [NSString stringWithFormat:@"%d bpm", maxs.intValue];
        
        NSString *min  = [NSString stringWithFormat:@"SELECT MIN(heartAve) AS OrderTotal FROM HeartModel WHERE dateString >='%@' and dateString <='%@' and heartAve >0 and user_id = '%@'", [time firstObject], [time lastObject], SN_USER.user_id];
        NSString *mins = [[HeartModel getUsingLKDBHelper]executeScalarWithSQL:min arguments:nil];
        heartMin = mins.integerValue == 0 ? @"--" : [NSString stringWithFormat:@"%d bpm", mins.intValue];
        
        NSString *ave  = [NSString stringWithFormat:@"SELECT AVG(heartAve) AS OrderTotal FROM HeartModel WHERE dateString >='%@' and dateString <='%@' and heartAve >0 and user_id = '%@'", [time firstObject], [time lastObject], SN_USER.user_id];
        NSString *aves = [[HeartModel getUsingLKDBHelper]executeScalarWithSQL:ave arguments:nil];
        heartAve = aves.integerValue == 0 ? @"--" : [NSString stringWithFormat:@"%d bpm", aves.intValue];
    }
    
    NSArray *array2 = [NSArray arrayWithObjects:heartAve, heartMax, heartMin, nil];
    
    if (array2.count > 0) {
        for (UILabel *label in _labelView.subviews) {
            if ([label isKindOfClass:[UILabel class]]) {
                if (label.tag >= 100) {
                    label.text = array2[label.tag - 100];
                    if (![label.text isEqualToString:@"--"]) {
                        [label setAttributedText:[SN_PublicClass label1With:label.text withFontsize:10.0 withChangeText1:@"bpm" withChangeText2:@"bpm"]];
                    }
                }
            }
        }
    }
}

- (void)updateView:(KKBLEAcceptType)type {
    if (type == KKBLEAcceptTypeDataHeart) {
        [self selectType:_type];
    }
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end

